package trading_strategy.events;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 6 mai 2010
 * Time: 17:25:16
 * To change this template use File | Settings | File Templates.
 */
public class EventProvider {
    final EventDispatcher dispatcher; // The worker that will be used to actually run the events
    final String name; // Name of the provider
    private Collection<EventListener> listeners = new ArrayList<EventListener>();

    public EventProvider(String name, String dispatcherName) {
        this.name = name;
        this.dispatcher = EventManager.getInstance().getDispatcher(dispatcherName);
    }

    public void addEvent(final AbstractMarketEvent event) {
        dispatcher.addEvent(new EventDispatcher.TimedRunnable(event.getTs()) {
            @Override
            public void run() {
                dispatchEvent(event);
            }
        });
    }

    private void dispatchEvent(AbstractMarketEvent event) {
        if (event != null) {
            for (EventListener listener : listeners) {
                listener.onMarketEvent(event);
            }
        }
    }

    public void addListener(EventListener listener) {
        synchronized (this) {
            // Copy the previous list and adds the new listener
            if (!listeners.contains(listener)) {
                final Collection<EventListener> eventListeners = listeners;
                ArrayList<EventListener> newListeners = new ArrayList<EventListener>(eventListeners);
                newListeners.add(listener);
                listeners = newListeners;
            }
        }
    }

    public void clear() {
        synchronized (this) {
            listeners.clear();
        }
    }

    public void removeListener(EventListener listener) {
        synchronized (this) {
            // Copy the previous list and adds the new listener
            if (listeners.contains(listener)) {
                final Collection<EventListener> eventListeners = listeners;
                ArrayList<EventListener> newListeners = new ArrayList<EventListener>(eventListeners);
                newListeners.remove(listener);
                listeners = newListeners;
            }
        }
    }
}
